package com.chongyahhh.security.security.configs.verification;

import com.chongyahhh.security.security.common.CommonAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.stereotype.Component;

/**
 * @Author chongyahhh
 * 验证码登录配置
 */
@Component
public class VerificationLoginConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final VerificationAuthenticationProvider verificationAuthenticationProvider;

    private final String VERIFICATION_LOGIN_URL = "/user/login";

    //@Qualifier("tokenAuthenticationDetailsSource")
    //private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;

    @Autowired
    public VerificationLoginConfig(VerificationAuthenticationProvider verificationAuthenticationProvider) {
        this.verificationAuthenticationProvider = verificationAuthenticationProvider;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        CommonAuthenticationFilter commonAuthenticationFilter = new CommonAuthenticationFilter(VERIFICATION_LOGIN_URL, new VerificationAuthenticationProcessor());
        // 使自定义的 Filter 可以获取到 ProviderManager
        commonAuthenticationFilter.setAuthenticationManager(http.getSharedObject((AuthenticationManager.class)));

        http
                .authenticationProvider(verificationAuthenticationProvider)
                // 注意自定义 Filter 插入的位置
                .addFilterAfter(commonAuthenticationFilter, ExceptionTranslationFilter.class);
    }
}
